package guava.sort;

import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: liuliwei
 * Date: 2017-07-03
 * Time: 上午11:13
 * Description: ${description}
 * guava 的排序 可以用多个条件来控制排序 ordering继承自comparator
 * 返回的list为一个排序过的新的集合，原有的集合顺序不变
 */
public class SortTest {
    static class Man {
        String name;
        int age;
        int height;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public int getHeight() {
            return height;
        }

        public void setHeight(int height) {
            this.height = height;
        }

        @Override
        public String toString() {
            return "Man{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", height=" + height +
                    '}';
        }
    }

    public static void main(String[] args) {
        Man a = new Man();
        Man b = new Man();
        a.setAge(1);
        a.setHeight(1);
        a.setName("111");
        b.setAge(332);
        b.setHeight(2);
        b.setName("2");
        Man c = new Man();
        c.setName("c");
        Man d= new Man();
        d.setName("d");
        c.setAge(100);
        d.setAge(100);
        c.setHeight(0);
        d.setHeight(20);

        List<Man> list = Lists.newArrayList(a, b, c,d);
        Ordering<Man> ageS = new Ordering<Man>() {
            @Override
            public int compare(Man left, Man right) {
                return left.getAge()-right.getAge();
            }
        } ;

        Ordering<Man> heightJ= new Ordering<Man>() {
            @Override
            public int compare(Man left, Man right) {
                return -(left.getHeight()-right.getHeight());
            }
        } ;

        Ordering<Man> namezr= new Ordering<Man>() {
            @Override
            public int compare(Man left, Man right) {
                return left.getName().compareTo(right.getName());
            }
        } ;

        Ordering<Man> ordering = Ordering.from(ageS).compound(heightJ).compound(namezr);
        Ordering<Man> ordering1 = ageS.compound(heightJ).compound(namezr);
        //打印排序过的集合
        System.out.println(ordering.sortedCopy(list));
        System.out.println(ordering1.sortedCopy(list));
        //原有集合顺序不变
        System.out.println(list);
    }
}
